using MediatR;
using Dapper;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.ProductionPlans;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ProductionPlans;
using System.Text;
using System;
using System.Collections.Generic;

namespace RBAC.Read.Api.Application.Handler.ProductionPlans
{
    public class GetProductionPlanCommandHandler : IRequestHandler<GetProductionPlanCommands, APIResult<APIPaging<ProductionPlanListDto>>>
    {
        private readonly IBaseRepository<ProductionPlan> _planRepo;

        public GetProductionPlanCommandHandler(IBaseRepository<ProductionPlan> planRepo)
        {
            _planRepo = planRepo;
        }

        public Task<APIResult<APIPaging<ProductionPlanListDto>>> Handle(GetProductionPlanCommands request, CancellationToken cancellationToken)
        {
            try
            {
                var pageIndex = request.PageIndex <= 0 ? 1 : request.PageIndex;
                var pageSize = request.PageSize <= 0 ? 10 : request.PageSize;

                var sbWhere = new StringBuilder("p.IsDeleted = 0");
                var param = new DynamicParameters();

                if (!string.IsNullOrWhiteSpace(request.PlanCode))
                {
                    sbWhere.Append(" AND p.PlanCode LIKE @PlanCode");
                    param.Add("PlanCode", $"%{request.PlanCode}%");
                }
                if (!string.IsNullOrWhiteSpace(request.PlanTopic))
                {
                    sbWhere.Append(" AND p.PlanTopic LIKE @PlanTopic");
                    param.Add("PlanTopic", $"%{request.PlanTopic}%");
                }

                var where = sbWhere.ToString();

                // total count
                var countSql = $"SELECT COUNT(1) FROM ProductionPlan p WHERE {where}";
                var total = _planRepo.QueryFirstOrDefault<int>(countSql, param);

                // data query with join to GoodsInfo for GoodOverview
                var dataSql = $@"
                                SELECT 
                                    p.Id,
                                    p.PlanCode,
                                    p.PlanTopic,
                                    p.DocumentsTime,
                                    TRIM(CONCAT_WS(' ', COALESCE(g.GoodName, ''), COALESCE(g.SpecificationModel, ''), COALESCE(g.Unit, ''))) AS GoodOverview,
                                    p.AssociatedProjects,
                                    p.Remark
                                FROM ProductionPlan p
                                LEFT JOIN GoodsInfo g ON g.Id = p.GoodsId AND g.IsDeleted = 0
                                WHERE {where}
                                ORDER BY p.Id DESC
                                LIMIT @Offset, @PageSize;";

                param.Add("Offset", (pageIndex - 1) * pageSize);
                param.Add("PageSize", pageSize);

                var raw = _planRepo.Query<dynamic>(dataSql, param);

                // map to dto and compute RowNo (序号)
                var list = new List<ProductionPlanListDto>();
                int startRow = (pageIndex - 1) * pageSize;
                int i = 0;
                foreach (var r in raw)
                {
                    list.Add(new ProductionPlanListDto
                    {
                        Id = r.Id,
                        RowNo = startRow + (++i),
                        PlanCode = r.PlanCode,
                        PlanTopic = r.PlanTopic,
                        DocumentsTime = r.DocumentsTime,
                        GoodOverview = r.GoodOverview,
                        AssociatedProjects = r.AssociatedProjects,
                        Remark = r.Remark
                    });
                }

                var paging = new APIPaging<ProductionPlanListDto>
                {
                    PageDatas = list,
                    TotalCount = total
                };

                return Task.FromResult(new APIResult<APIPaging<ProductionPlanListDto>>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = paging
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<APIPaging<ProductionPlanListDto>>
                {
                    Code = APIEnums.Fail,
                    Msg = "查询失败：" + ex.Message,
                    Data = new APIPaging<ProductionPlanListDto>()
                });
            }
        }
    }
}

